package com.songcha.sakura.mvvm.comic.search

import android.app.Application
import androidx.lifecycle.MutableLiveData
import com.songcha.library_base.interfaces.IApiResult
import com.songcha.library_base.mvvm.base.BaseRefreshLoadMoreViewModel
import com.songcha.library_base.mvvm.base.BaseRepository
import com.songcha.sakura.bean.ComicListBean
import com.songcha.library_database_sakura.greendao.GreenDaoManager
import com.songcha.library_database_sakura.greendao.SearchHistoryBean
import org.greenrobot.greendao.query.WhereCondition

class ComicSearchViewModel(app: Application) : BaseRefreshLoadMoreViewModel<ComicSearchRepository, ComicListBean.ComicBean>(app) {
    //private val _comicM3u8Url = MutableLiveData<ComicM3u8Bean>()
    //val comicM3u8Url: MutableLiveData<ComicM3u8Bean> = _comicM3u8Url
    //val comicList = MutableLiveData<ComicListBean>()

    fun searchComic(key:String){
        handleApiDataObserver((repository!!).getComicList(key,currentPage),object :
            IApiResult<ComicListBean> {
            override fun onSuccess(bean: ComicListBean) {
                handleDataListSuccess(bean.data)
                /*handleDataListSuccess(bean.data,object : IOnHandleDataListCallback{
                    override fun onUpdate() {
                        comicList.value=bean
                    }

                    override fun onAppendList() {
                        val tmp=comicList.value
                        tmp!!.data.addAll(bean.data)
                        comicList.value=tmp!!
                    }

                })*/

            }

        },true)

    }



    fun saveSearchHistory(key:String){
        val searchHistoryDao= GreenDaoManager.getInstance().searchHistoryDao
        //if size>=10,del size-9,insert
        val qb=searchHistoryDao.queryBuilder()
        val list=qb.list()
        if(list.size>=10){
            val delSize=list.size-9
            qb.where(
                WhereCondition.StringCondition("_id in " +
                    "(select _id from SEARCH_HISTORY_BEAN order by _id limit $delSize)"))
            qb.buildDelete().executeDeleteWithoutDetachingEntities()
        }

        val bean= SearchHistoryBean()
        bean.title=key
        searchHistoryDao.insertOrReplace(bean)
    }

}